package com.android.taobao.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.taobao.api.model.ItemCat;

public class DataBase {
	private static final String DATABASE_NAME = "taobaoonandroid.db";

	private static final String SQL_CREATE_TABLE_ITEM_CATS = "CREATE TABLE IF NOT EXISTS ITEM_CATS("
			+ "cid TEXT PRIMARY KEY,"
			+ "name TEXT,"
			+ "status TEXT,"
			+ "sort_order INTEGER,"
			+ "parent_cid TEXT,"
			+ "is_parent BOOL "
			+ ");";

	private Context ctx;

	private static DataBase database;

	private DataBase(Context ctx) {
		this.ctx = ctx;
		SQLiteDatabase db = openDB();
		db.execSQL(SQL_CREATE_TABLE_ITEM_CATS);
		db.close();
	}

	private SQLiteDatabase openDB() {
		return ctx.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE,
				null);
	}

	public static DataBase getInstance(Context ctx) {
		if (database == null) {
			database = new DataBase(ctx);
		}
		return database;
	}

	public void saveOrUpdateItemCats(ItemCat cat) {
		ContentValues values = new ContentValues();
		values.put("name", cat.getName());
		values.put("status", cat.getStatus());
		values.put("sort_order", cat.getSortOrder());
		values.put("parent_cid", cat.getParentCid());
		values.put("is_parent", cat.getIsParent());

		SQLiteDatabase db = openDB();
		if (null == getItemCat(cat.getCid())) {// insert
			values.put("cid", cat.getCid());
			db.insert("ITEM_CATS", null, values);
		} else {// update
			db.update("ITEM_CATS", values, "cid=" + cat.getCid(), null);
		}
		db.close();
	}

	public ItemCat getItemCat(String cid) {
		ItemCat cat = null;
		SQLiteDatabase db = openDB();
		Cursor c = db.query("ITEM_CATS", null, "cid=" + cid, null, null, null,
				null);
		if (c.moveToFirst()) {
			cat = buildItemCat(c);
		}
		c.close();
		db.close();
		return cat;
	}

	private ItemCat buildItemCat(Cursor c) {
		ItemCat cat = new ItemCat();
		cat.setCid(c.getString(0));
		cat.setName(c.getString(1));
		cat.setStatus(c.getString(2));
		cat.setSortOrder(c.getInt(3));
		cat.setParentCid(c.getString(4));
		cat.setIsParent(1 == c.getInt(5));
		return cat;
	}
}